package cn.lzx.user.service.impl;

import cn.lzx.basic.excpetion.BusinessExcpetion;
import cn.lzx.basic.service.impl.BaseServiceImpl;
import cn.lzx.basic.util.MD5Utils;
import cn.lzx.basic.util.StrUtils;
import cn.lzx.user.domain.Logininfo;
import cn.lzx.user.domain.User;
import cn.lzx.user.domain.UserDto;
import cn.lzx.user.mapper.LogininfoMapper;
import cn.lzx.user.mapper.UserMapper;
import cn.lzx.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * UserService实现类
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 注入redis 用于保存验证码 获取验证码 刷新时间
     */
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    /**
     * 后台发短信的方法
     * @param phone
     */
    @Override
    public void sendSms(String phone) {
        //判断传入的电话号码是否为空
        if (!StringUtils.hasLength(phone)) {
            throw new BusinessExcpetion("请输入正确的手机号");
        }
        //根据电话号码去user中查询 这个电话是否存在 如果存在就说明已经注册不能重复注册
        User user = userMapper.findByPhone(phone);
        if (user!=null){
            throw new BusinessExcpetion("该用户已经注册,请直接登录");
        }
        //获取redis中保存的验证码"register:" + phone 相当于就是redis中保存验证码的key值 根据key获取vaule
        //vaule的格式是 验证码:时间戳 的格式
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        String code=null;
        if (obj!=null){
            //获取redis中以前保存的验证码 因为redis保存验证码是  验证码:时间戳 的格式
            //所以用:分割  第一个值就是验证码  第二给值就是时间戳
            code = obj.toString().split(":")[0];
            String time = obj.toString().split(":")[1];
            //如果当前时间戳减去用户点击重发按钮时的时间戳 小于一分钟 即60000毫秒 就反馈一个不能重复发送验证码
            if (System.currentTimeMillis()-Long.parseLong(time)<60000){
                throw new BusinessExcpetion("不能重复发送验证码");
            }
        }else{
            //重新生成验证码
            code = StrUtils.getRandomString(6);
        }
        /**
         * redis中保存验证码
         * key = "register:" + phone
         * value= code +":" +System.currentTimeMillis(), 验证码:时间戳
         * 时间为3, 单位是分钟 TimeUnit.MINUTES
         */
        redisTemplate.opsForValue().set("register:" + phone,code +":" +System.currentTimeMillis(),3,TimeUnit.MINUTES);
        /**
         * 因为我们没有那么多短信 所以用后端打印接收一下验证码
         * 下面这句才是真正发验证码的方法
         * SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",请在3分钟之内使用");
         */
        System.out.println(code);


    }

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String verifycode = userDto.getVerifycode();
        String password = userDto.getPassword();
        String repassword = userDto.getRepassword();
        //1.校验
        //1.1.空值校验 - StringUtils.isEmpty()
        if (StringUtils.isEmpty(phone)||
                StringUtils.isEmpty(verifycode)||
                StringUtils.isEmpty(password)||
                StringUtils.isEmpty(repassword)){
        throw new BusinessExcpetion("请输入正确的数据");
        }
        //1.2.两次密码是否相同 - equals()
        if(!password.equals(repassword)){
            throw new BusinessExcpetion("两次密码不一致");
        }
        //1.3.验证码是否过期 - redis【null】
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj==null){
            throw new BusinessExcpetion("验证码无效");
        }
        //1.4.验证码是否正确 - redis的验证码与前端传递过来的验证🐎【忽略大小写】
        String code = obj.toString().split(":")[0];
        if (!code.equals(verifycode)){
            throw new BusinessExcpetion("请输入正确的验证码");
        }
        //1.5.手机号码是否已经被注册了
        User userTmp = userMapper.findByPhone(phone);
        if (userTmp!=null){
            throw new BusinessExcpetion("该用户已经注册,请直接登录");
        }
        //2.保存数据
        //2.1.先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        //2.2.再保存t_user
        user.setLogininfo(logininfo);
        userMapper.save(user);


    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5pwd);
        return user;

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }



}
